'''
Created on Jan 27, 2013

@author: kafkef
'''



from PyQt4.QtGui import *
from PyQt4.QtCore import SIGNAL, Qt

from dexen.system import client
from dexen.system.client.ui.remote.table import RemoteTable


svr_proxy = client.GetServerProxy()


class SlavesInfoWdg(QWidget):
    def __init__(self):
        super(SlavesInfoWdg, self).__init__()
        self._create_widgets()

    def _create_widgets(self):
        self.refreshBtn = QPushButton("Refresh")
        self.refreshBtn.setEnabled(False)
        self.slavesTable = RemoteTable("SlavesInfoWdg")
        self.slavesTable.setColumnCount(3)
        self.slavesTable.setHorizontalHeaderLabels(["Node Name", "Slave Name", "Status"])
        hLayout = QHBoxLayout()
        hLayout.addStretch()
        hLayout.addWidget(self.refreshBtn)
        
        layout = QVBoxLayout()
        layout.addLayout(hLayout)
        layout.addWidget(self.slavesTable)
        
        self.setLayout(layout)
        
        self.connect(self.refreshBtn, SIGNAL("clicked()"), self.get_slave_states)
    
    def get_slave_states(self):
        node_states = svr_proxy.get_node_states()
        slave_states = []
        for node_state in node_states:
            slave_states.extend(node_state.slave_states)
        
        self.slavesTable.setRowCount(len(slave_states))
        self.slavesTable.setSortingEnabled(False)    
        for row, slave_state in enumerate(slave_states):
            self.slavesTable.setItem(row, 0, QTableWidgetItem(slave_state.node_name))
            self.slavesTable.setItem(row, 1, QTableWidgetItem(slave_state.name))
            self.slavesTable.setItem(row, 2, QTableWidgetItem(str(slave_state.state)))
        self.slavesTable.setSortingEnabled(True)
    
    def on_connect(self):
        self.refreshBtn.setEnabled(True)

    def on_disconnect(self):
        self.refreshBtn.setEnabled(False)
        self.slavesTable.setRowCount(0)
    
    def save_settings(self):
        self.slavesTable.save_settings()
    
    def restore_settings(self):
        self.slavesTable.restore_settings()
        
"""
    @pyqtSlot(result=str)
    def get_master_states_json(self):
        master_states = []
        node_states = svr_proxy.get_node_states()
        for node_state in node_states:
            for master_state in node_state.master_states:
                master_states.append([master_state.node_name, 
                                      master_state.master_name,
                                      master_state.job_name,
                                      master_state.get_state(),
                                      master_state.get_num_inds()])
        print json.dumps(master_states)
        return json.dumps(master_states)

"""